package com.ruoyi.video.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.file.FileExistsException;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.video.domain.VideoFile;
import com.ruoyi.video.service.IVideoFileService;
import com.ruoyi.video.service.IVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * 番剧文件Controller
 *
 * @author ruoyi
 * @date 2022-02-04
 */
@RestController
@RequestMapping("/video/videoFile")
public class VideoFileController extends BaseController {
    @Autowired
    private IVideoFileService videoFileService;

    @Autowired
    private IVideoService videoService;

    /**
     * 查询番剧文件列表
     */
    @PreAuthorize("@ss.hasPermi('video:videoFile:list')")
    @GetMapping("/list")
    public TableDataInfo list(VideoFile videoFile) {
        startPage();
        List<VideoFile> list = videoFileService.selectVideoFileList(videoFile);
        list.forEach(v -> v.setFilePath(null));
        return getDataTable(list);
    }

    /**
     * 导出番剧文件列表
     */
    @PreAuthorize("@ss.hasPermi('video:videoFile:export')")
    @Log(title = "番剧文件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, VideoFile videoFile) {
        List<VideoFile> list = videoFileService.selectVideoFileList(videoFile);
        ExcelUtil<VideoFile> util = new ExcelUtil<VideoFile>(VideoFile.class);
        util.exportExcel(response, list, "番剧文件数据");
    }

    /**
     * 获取番剧文件详细信息
     */
    @PreAuthorize("@ss.hasPermi('video:videoFile:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        VideoFile videoFile = videoFileService.selectVideoFileById(id);
        if (Objects.isNull(videoFile)) {
            return AjaxResult.error("没有此视频");
        }
        videoFile.setFilePath(null);
        return AjaxResult.success(videoFile);
    }

    /**
     * 获取番剧 文件 列表 历史 关联
     */
    @PreAuthorize("@ss.hasPermi('video:videoFile:query')")
    @PostMapping(value = "/getVideoAllInfo")
    public AjaxResult getVideoAllInfo(@RequestBody VideoFile videoFile) {
        HashMap<String, Object> allInfo = videoFileService.getVideoAllInfo(videoFile);
        return Objects.isNull(allInfo) ? AjaxResult.error() : AjaxResult.success(allInfo);
    }

    /**
     * 新增番剧文件
     */
    @PreAuthorize("@ss.hasPermi('video:videoFile:add')")
    @Log(title = "番剧文件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody VideoFile videoFile) {
        if (StringUtils.isEmpty(videoFile.getId())) videoFile.setId(IdUtils.fastUUID());
        return toAjax(videoFileService.insertVideoFile(videoFile));
    }

    /**
     * 新增番剧文件s
     */
    @PreAuthorize("@ss.hasPermi('video:videoFile:add')")
    @Log(title = "番剧文件", businessType = BusinessType.INSERT)
    @PostMapping("batchSave")
    public AjaxResult batchSave(@RequestBody List<VideoFile> videoFile) {
        if (videoFile.size() == 0) return AjaxResult.noHaveParam();
        //新添加的
        ArrayList<VideoFile> videoFiles = new ArrayList<>();
        //原来的
        ArrayList<VideoFile> videoFiles2 = new ArrayList<>();
        //补全数据
        for (int i = 0; i < videoFile.size(); i++) {
            VideoFile file = videoFile.get(i);
            file.setSort(i);
            file.setVideoNumber(i + 1 + "");
            if (StringUtils.isEmpty(file.getId())) {
                file.setId(IdUtils.fastUUID());
                videoFiles.add(file);
            } else {
                videoFiles2.add(file);
            }
        }
        videoFileService.moveFile(videoFiles);
        int row = 0;
        for (VideoFile file : videoFiles2) {
            row += videoFileService.updateVideoFile(file);
        }
        row += videoFileService.batchSave(videoFiles);
        return toAjax(row);
    }

    /**
     * 修改番剧文件
     */
    @PreAuthorize("@ss.hasPermi('video:videoFile:edit')")
    @Log(title = "番剧文件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody VideoFile videoFile) {
        return toAjax(videoFileService.updateVideoFile(videoFile));
    }

    /**
     * 删除番剧文件
     */
    @PreAuthorize("@ss.hasPermi('video:videoFile:remove')")
    @Log(title = "番剧文件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(videoFileService.deleteVideoFileByIds(ids));
    }

    /**
     * 番剧视频上传
     */

    @PreAuthorize("@ss.hasPermi('video:videoFile:add')")
    @Log(title = "番剧视频上传", businessType = BusinessType.INSERT)
    @PostMapping("/videoUpload")
    public AjaxResult videoUpload(@RequestParam("video") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            try {
                String path = FileUploadUtils.upload(FileUtils.splicingFilePath(RuoYiConfig.getVideoPath(), "videoTemporary"), file, new String[]{"mkv", "mp4", "mov", "flv"});
                return AjaxResult.success(path);
            } catch (InvalidExtensionException e) {
                logger.error("番剧视频上传出错", e);
                return AjaxResult.error("仅支持mkv,mp4,mov,flv类型文件上传");
            } catch (FileExistsException e) {
                return AjaxResult.error(e.getCode());
            }
        }
        return AjaxResult.error("上传文件异常");
    }

    /**
     * 获取视频流
     *
     * @param videoId 视频id
     */

    //@PreAuthorize("@ss.hasPermi('video:videoFile:list')")
    @GetMapping("/getVideo/{videoId}")
    public void getVideo(@PathVariable String videoId) {
        videoFileService.getVideo(videoId, ServletUtils.getRequest(), ServletUtils.getResponse());
    }

    @GetMapping("/getSubtitle/{videoId}")
    public void getSubtitle(@PathVariable String videoId) {
        videoFileService.getSubtitle(videoId, ServletUtils.getRequest(), ServletUtils.getResponse());
    }

    @GetMapping("/getSubtitleWeb/{videoId}")
    public void getSubtitleWeb(@PathVariable String videoId) {
        videoFileService.getSubtitle(videoId, ServletUtils.getRequest(), ServletUtils.getResponse());
    }


    /**
     * 番剧头图上传
     */
    @Log(title = "番剧字幕上传", businessType = BusinessType.UPDATE)
    @PostMapping("/subtitleUpload")
    public AjaxResult subtitleUpload(@RequestParam("subtitle") MultipartFile file, VideoFile videoFile) throws IOException {
        if (Objects.isNull(videoFile) || StringUtils.isEmpty(videoFile.getId()) || file.isEmpty()) {
            return AjaxResult.noHaveParam();
        }
        videoFile = videoFileService.selectVideoFileById(videoFile.getId());
        if (Objects.isNull(videoFile)) return AjaxResult.error("文件不存在");
        try {
            File file1 = new File(videoFile.getFilePath()).getParentFile();
            if (!file1.exists()) {
                file1.mkdirs();
            }
            String absolutePath = file1.getAbsolutePath();
            String avatar = FileUploadUtils.upload(absolutePath, file, new String[]{"ass", "ssa", "srt"}, false, false);
            videoFile.setSubtitleName(file.getOriginalFilename());
            videoFile.setSubtitleExtendedName("text/plain");
            videoFile.setSubtitlePath(FileUtils.splicingFilePath(absolutePath, file.getOriginalFilename()));
            if (videoFileService.updateVideoFile(videoFile) == 1) {
                return AjaxResult.success(videoFile);
            }
        } catch (InvalidExtensionException e) {
            logger.error("番剧字幕上传出错", e);
        }
        return AjaxResult.error("上传字幕异常");
    }
}
